//package cn.nfwx.tv.controller;
//
//import android.app.Activity;
//import android.os.Handler;
//import android.os.Message;
//import android.support.v4.app.Fragment;
//import android.text.InputFilter;
//import android.text.TextUtils;
//import android.util.Log;
//import android.view.View;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.LinearLayout;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.TypeReference;
//import com.google.gson.Gson;
//import com.kaopiz.kprogresshud.KProgressHUD;
//import com.tencent.mm.opensdk.modelmsg.SendAuth;
//import com.tencent.mm.opensdk.openapi.IWXAPI;
//import com.tencent.mm.opensdk.openapi.WXAPIFactory;
//
//import org.greenrobot.eventbus.EventBus;
//import org.json.JSONObject;
//
//import cn.nfwx.tv.R;
//import cn.nfwx.tv.base.BaseFragment;
//import cn.nfwx.tv.base.NFWXApplication;
//import cn.nfwx.tv.callback.ResponseCallback;
//import cn.nfwx.tv.callback.ResponseListener;
//import cn.nfwx.tv.callback.ResponseWithFailListener;
//import cn.nfwx.tv.callback.UserCallBack;
//import cn.nfwx.tv.conts.Constants;
//import cn.nfwx.tv.events.LoginEvents;
//import cn.nfwx.tv.events.ToLoginEvents;
//import cn.nfwx.tv.events.ToMineItemEvent;
//import cn.nfwx.tv.fragment.me.MineFragment;
//import cn.nfwx.tv.helper.AccountHelper;
//import cn.nfwx.tv.helper.DialogFragmentHelper;
//import cn.nfwx.tv.helper.EditNullFilter;
//import cn.nfwx.tv.helper.NetworkHelper;
//import cn.nfwx.tv.helper.ValueCallback;
//import cn.nfwx.tv.helper.WifiHelper;
//import cn.nfwx.tv.manager.UserManager;
//import cn.nfwx.tv.model.Result;
//import cn.nfwx.tv.model.User;
//import cn.nfwx.tv.model.UserModel;
//import cn.nfwx.tv.util.LogUtil;
//import cn.nfwx.tv.util.NetworkUtil;
//import cn.nfwx.tv.util.SharePrefUtil;
//import cn.nfwx.tv.util.ToastUtil;
//import cn.nfwx.tv.util.ToolUtil;
//import cn.nfwx.tv.vo.ResultErrorVo;
//
///**
// * Created by zb.liu on 2017/11/20.
// */
//
//public class SMSLoginViewController implements View.OnClickListener, NetworkHelper.NetworkStateListener {
//    private final static String TAG_LOG = SMSLoginViewController.class.getSimpleName();
//    private Activity activity;
//    private EditText et_login_sms_phone, et_login_sms_code;
//    private TextView btn_login_sms_code;
//    private Button btn_login_sms;
//    private KProgressHUD smsProgress, loginSmsProgress;
//    private int countDown = 60;
//    private final int MSG_COUNT_LOGIN = 1;//短信登录
//    private TextView login_by_account, register_fast;
//    private LinearLayout login_wechat_lin;
//    private IWXAPI iwxapi;
//    private View login_wechat_lin_view;
//    private Fragment mFragment;
//    private boolean canSendSms = true;
//
//    public SMSLoginViewController(Activity activity, BaseFragment fragment, View view) {
//        this.activity = activity;
//        mFragment = fragment;
//        initView(view);
//        NetworkHelper.getInstance().addListener(this);
//    }
//
//    public void initView(View view) {
//        login_wechat_lin_view = findView(view, R.id.login_wechat_lin_view);
//        et_login_sms_phone = findView(view, R.id.et_login_sms_phone);
//        et_login_sms_code = findView(view, R.id.et_login_sms_code);
//        btn_login_sms_code = findView(view, R.id.btn_login_sms_code);
//        btn_login_sms = findView(view, R.id.btn_login_sms);
//        login_by_account = findView(view, R.id.login_by_account);
//        register_fast = findView(view, R.id.register_fast);
//        login_wechat_lin = findView(view, R.id.login_wechat_lin);
//        btn_login_sms_code.setOnClickListener(this);
//        btn_login_sms.setOnClickListener(this);
//        login_by_account.setOnClickListener(this);
//        register_fast.setOnClickListener(this);
//        login_wechat_lin.setOnClickListener(this);
//        et_login_sms_phone.setFilters(new InputFilter[]{new EditNullFilter()});
//        et_login_sms_code.setFilters(new InputFilter[]{new EditNullFilter()});
//        ToolUtil.toCheckPhone(activity, et_login_sms_phone, 1, new ValueCallback<Boolean>() {
//            @Override
//            public void onReceiveValue(Boolean value) {
//                canSendSms = value;
//            }
//        });
//        ToolUtil.toSetEditTextLength(activity, et_login_sms_code, 6);
//        iwxapi = NFWXApplication.getInstance().getIwxapi();
//        if (NetworkUtil.getNetworkType(activity) == NetworkUtil.WIFI_NETWORK) {
//            WifiHelper.getInstance()._testIfNeedLogon(new ValueCallback<Boolean>() {
//                @Override
//                public void onReceiveValue(Boolean value) {
//                    if (value) {
//                        shandler.sendEmptyMessage(0);
//                    } else {
//                        shandler.sendEmptyMessage(1);
//                    }
//                }
//            }, "wifi");
//        } else {
//            login_wechat_lin.setVisibility(View.VISIBLE);
//        }
//    }
//
//    /**
//     * 查找控件
//     *
//     * @param rid
//     * @param <T>
//     * @return
//     */
//    public <T extends View> T findView(View view, int rid) {
//        return (T) view.findViewById(rid);
//    }
//
//    @Override
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.btn_login_sms_code:
//                String smsMobileNo = et_login_sms_phone.getText().toString().trim();
//                if (TextUtils.isEmpty(smsMobileNo)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_phone), Toast.LENGTH_LONG).show();
//                    return;
//                }
//                if (!ToolUtil.isPhoneLegal(smsMobileNo)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_right_phone), Toast.LENGTH_LONG).show();
//                    return;
//                }
//                btn_login_sms_code.setClickable(false);//防止重复点击Button，否则多次点击button：每隔一秒发送消息多次执行
//                countDown = 60;
//                if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {
//                    smsProgress = KProgressHUD.create(activity)
//                            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
////                        .setLabel("加载中")
////                        .setDetailsLabel("Downloading data")
//                            .setCancellable(true)
//                            .setAnimationSpeed(2)
//                            .setDimAmount(0.5f);
//                    smsProgress.show();
//                    UserManager.requestSmsCode(activity, smsMobileNo, "login", new ResponseWithFailListener<JSONObject>() {
//                        @Override
//                        public void onResponse(String tag, final JSONObject response) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    handler.sendEmptyMessage(MSG_COUNT_LOGIN);
//                                    Toast.makeText(activity, "短信已发送", Toast.LENGTH_LONG).show();
//                                    btn_login_sms_code.setClickable(true);
//                                    smsProgress.dismiss();
//                                }
//                            });
//
//
//                        }
//
//
//                        @Override
//                        public void onError(String tag, Throwable t) {
//
//
//                        }
//
//                        @Override
//                        public void onFail(String requestTag, final String response) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    try {
//                                        Gson gson = new Gson();
//                                        ResultErrorVo resultErrorVo = gson.fromJson(response, ResultErrorVo.class);
//                                        btn_login_sms_code.setClickable(true);
//                                        smsProgress.dismiss();
//                                        Toast.makeText(activity, "null".equals(resultErrorVo.getMsg()) ? "短信验证码发送失败" : resultErrorVo.getMsg(), Toast.LENGTH_LONG).show();
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onFinish() {
//                            smsProgress.dismiss();
//                        }
//                    });
//                } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
//                    if (!canSendSms) {
//                        Toast.makeText(activity, "该号码未注册", Toast.LENGTH_LONG).show();
//                        return;
//                    }
//                    DialogFragmentHelper.showLoadingDialog(mFragment.getChildFragmentManager());
//                    UserManager.requestIjkSmsCode(activity, smsMobileNo, new ResponseCallback<Integer>() {
//                        @Override
//                        public void onSuccess(String requestTag, final Integer response) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    btn_login_sms_code.setClickable(true);
//                                    DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
//                                    if (response > 0) {
//                                        handler.sendEmptyMessage(MSG_COUNT_LOGIN);
//                                        Toast.makeText(activity, "短信已发送", Toast.LENGTH_LONG).show();
//                                    } else {
//                                        ToastUtil.show(activity, "短信发送失败");
//                                    }
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onFailure(String requestTag, String message) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
//                                    btn_login_sms_code.setClickable(true);
//                                    ToastUtil.show(activity, "短信发送失败");
//                                }
//                            });
//                        }
//                    });
//                }
//                break;
//            case R.id.btn_login_sms:
//                final String smsLoginPhone = et_login_sms_phone.getText().toString().trim();
//                if (TextUtils.isEmpty(smsLoginPhone)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_phone), Toast.LENGTH_LONG).show();
//                    return;
//                }
//                if (!ToolUtil.isPhoneLegal(smsLoginPhone)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_right_phone), Toast.LENGTH_LONG).show();
//                    return;
//                }
//                String smsLoginCode = et_login_sms_code.getText().toString();
//                if (TextUtils.isEmpty(smsLoginCode)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_code), Toast.LENGTH_LONG).show();
//                    return;
//                }
//                if (smsLoginCode.length() != 6 || !ToolUtil.isNumeric(smsLoginCode)) {
//                    Toast.makeText(activity, activity.getResources().getString(R.string.toast_code_length), Toast.LENGTH_LONG).show();
//                    return;
//                }
//
//                if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {
//                    loginSmsProgress = KProgressHUD.create(activity)
//                            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//                            .setCancellable(true)
//                            .setAnimationSpeed(2)
//                            .setDimAmount(0.5f);
//                    loginSmsProgress.show();
//                    UserManager.loginBySms(activity, smsLoginPhone, smsLoginCode, new UserCallBack() {
//                        @Override
//                        public void onSuccess(final UserModel userModel) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    SharePrefUtil.saveUser(activity.getApplicationContext(), userModel);//缓存用户数据
//                                    EventBus.getDefault().post(new LoginEvents(userModel));
//                                    Toast.makeText(activity, "登录成功", Toast.LENGTH_LONG).show();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onFail(String code, final String response) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Log.d("onFail", response);
//                                    Gson gson = new Gson();
//                                    ResultErrorVo resultErrorVo = gson.fromJson(response, ResultErrorVo.class);
//                                    Toast.makeText(activity, resultErrorVo.getMsg(), Toast.LENGTH_LONG).show();
//                                    loginSmsProgress.dismiss();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onError(String tag, Throwable t) {
//                            super.onError(tag, t);
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    //    Toast.makeText(activity,"登录失败",Toast.LENGTH_LONG).show();
//                                    loginSmsProgress.dismiss();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onComplete() {
//                            super.onComplete();
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    loginSmsProgress.dismiss();
//                                }
//                            });
//
//                        }
//                    });
//                } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
//                    if (!canSendSms) {
//                        Toast.makeText(activity, "该号码未注册", Toast.LENGTH_LONG).show();
//                        return;
//                    }
//                    DialogFragmentHelper.showLoadingDialog(mFragment.getChildFragmentManager());
//                    UserManager.requestIjkRegister(activity, smsLoginPhone, "", "", smsLoginCode, new ResponseListener<JSONObject>() {
//                        @Override
//                        public void onResponse(String requestTag, final JSONObject response) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
//                                    Result<User> result = JSON.parseObject(response.toString(), new TypeReference<Result<User>>() {
//                                    }.getType());
//                                    if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
//                                        if (result.getData() != null && result.getData().getUid() != 0) {
//                                            AccountHelper.getInstance().saveUser(activity, result.getData());
//                                            ToastUtil.show(activity, "登录成功", Toast.LENGTH_LONG);
//
//                                            EventBus.getDefault().post(new ToMineItemEvent(MineFragment.POSITION_SUBSCRIPT));
//                                        }
//                                    } else {
//                                        ToastUtil.show(activity, result.getMessage());
//                                    }
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onError(String requestTag, Throwable t) {
//                            activity.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
//                                    ToastUtil.show(activity, "登录失败");
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onFinish() {
//
//                        }
//                    });
//                }
//                break;
//            case R.id.register_fast:
//                EventBus.getDefault().post(new ToLoginEvents(1));
//                break;
//            case R.id.login_by_account:
//                EventBus.getDefault().post(new ToLoginEvents(0));
//                break;
//            case R.id.login_wechat_lin:
//                SendAuth.Req req = new SendAuth.Req();
//                req.scope = "snsapi_userinfo";
//                req.state = "nfwx";
//                iwxapi.sendReq(req);
//                break;
//
//        }
//    }
//
//    public Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case MSG_COUNT_LOGIN:
//                    if (countDown >= 0) {
//                        btn_login_sms_code.setText(countDown-- + "s");
//                        handler.sendEmptyMessageDelayed(MSG_COUNT_LOGIN, 1000);
//                    } else {
//                        btn_login_sms_code.setClickable(true);
//                        countDown = 60;//复位，60s倒计时完后可以继续倒计时
//                        btn_login_sms_code.setText("获取验证码");
//                    }
//                    break;
//
//            }
//
//        }
//    };
//
//    @Override
//    public void onNetworkChange(int networkType) {
//        if (NetworkUtil.getNetworkType(activity) == NetworkUtil.WIFI_NETWORK) {
//            WifiHelper.getInstance()._testIfNeedLogon(new ValueCallback<Boolean>() {
//                @Override
//                public void onReceiveValue(Boolean value) {
//                    if (value) {
//                        shandler.sendEmptyMessage(0);
//                    } else {
//                        shandler.sendEmptyMessage(1);
//                    }
//                }
//            }, "wifi");
//        } else {
//            login_wechat_lin.setVisibility(View.VISIBLE);
//        }
//    }
//
//    public void onDestroy() {
//        NetworkHelper.getInstance().removeListener(this);
//    }
//
//    Handler shandler = new Handler() {
//        @Override
//        public void dispatchMessage(Message msg) {
//            super.dispatchMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    login_wechat_lin.setVisibility(View.VISIBLE);
//                    login_wechat_lin_view.setVisibility(View.VISIBLE);
//                    break;
//                case 1:
//                    login_wechat_lin.setVisibility(View.INVISIBLE);
//                    login_wechat_lin_view.setVisibility(View.INVISIBLE);
//                    break;
//            }
//
//        }
//    };
//}
